// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.chips;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class CompiledChip implements Chip {
  public int ADDRESS = 0;
  public byte DATA = 0;
  public boolean DATA_ACTIVE = false;
  public boolean WR = false;
  public boolean REQ = false;
  
  private int address = 0;
  private boolean read = false;  

  private final int mask;
  final byte[] mem;
  
  public CompiledChip(int addressBits) {
    this.mask = (1 << addressBits) - 1;
    this.mem = new byte[1 << addressBits];
  }

  public void update() {
    // Incrementor
    if (read) {
      ADDRESS = address;
      DATA_ACTIVE = false;
      WR = false;
      REQ = true;
    } else {
      DATA++;
      DATA_ACTIVE = true;
      ADDRESS = address++;
      WR = true;
      REQ = true;
    }
    read = !read;

    // Memory
    DATA_ACTIVE = false;
    if (REQ) {
      if (WR) {
        mem[ADDRESS & mask] = DATA;
      } else {
        DATA = mem[ADDRESS & mask];
        DATA_ACTIVE = true;
      }
    }
  }
}
